import "https://cdn.bootcdn.net/ajax/libs/jquery/1.12.4/jquery.min.js"


// 登录状态判定切换用户状态
function loginState() {
    const user = $(".username")
    const back = $(".backlogin")
    const login = $(".login")
    const register = $(".register")
    if (localStorage.getItem("username")) {
        user.show()
        back.show()
        login.hide()
        register.hide()
        user.find("i").html(localStorage.getItem("username"))
    } else {
        user.hide()
        back.hide()
        login.show()
        register.show()
    }

    back.on("click", function() {
        localStorage.removeItem("username")
        user.hide()
        back.hide()
        login.show()
        register.show()
    })
}

// 二级菜单效果 并且实现拖动滚动条完整显示二级菜单里面的内容
function twoMenu() {
    const menus = $(".banner_menu li")
    const submenus = $(".sub_menu")
    const oUl = $(".banner_menu")

    // console.log(menus, submenus)
    menus.on("mouseenter", function() { // 鼠标移入主菜单事件
        //console.log($(this).index()) // 这里的$(this).index()方法只能用于是兄弟元素的元素对象集合
        $(".banner_menu").find(".sub_menu").hide()
        submenus.eq($(this).index()).show()

        // 拖动游览器滚动条完整显示二级菜单里面的内容
        let scrollTop = $(window).scrollTop()
        let bannerTop = oUl.offset().top
        if (scrollTop > bannerTop) {
            submenus.eq($(this).index()).css({
                top: scrollTop - bannerTop
            })
        } else { // 滚动条距离没有超过二级菜单父级定位盒子的offsetTop值 
            submenus.eq($(this).index()).css({
                top: 0
            })
        }
    })
    menus.on("mouseleave", function() { // 鼠标离开主菜单事件
        $(".banner_menu").find(".sub_menu").hide()
    })

    submenus.hover(function() {
        $(this).show()
    }, function() {
        $(this).hide()
    })
}

// 头部搜索导航区域下拉滚动条固定在首部
function fixedHead() {
    let t = $(".h_con").offset().top
    let height = $(".h_con").outerHeight()
    const head = $(".h_con")
    if (document.querySelector("#index")) {
        let bannerHeight = $(".banner").outerHeight()
        $(window).scroll(function() { //窗口滚动条滚动事件
            let top = $(window).scrollTop()
            if (top >= t + height + bannerHeight) {
                head.css({
                    position: "fixed",
                    top: 0,
                    zIndex: 1000
                })
            } else {
                head.css({
                    position: "relative"
                })
            }
        })
    } else {
        $(window).scroll(function() { //窗口滚动条滚动事件
            let top = $(window).scrollTop()
            if (top >= t + height) {
                head.css({
                    position: "fixed",
                    top: 0,
                    zIndex: 1000
                })
            } else {
                head.css({
                    position: "relative"
                })
            }
        })
    }
}

// 点击购物车按钮，判断是否登录如果未进行登录提示用户是否登录，如果已登录则跳转至购物车页面
function carbuy() {
    const buycar = $(".buycar")
    buycar.on("click", function() {
        if (localStorage.getItem("username")) {
            $(this).attr("href", "cartlist.html")
        } else {
            if (window.confirm("您还未进行登录，确认进入登录界面吗?")) {
                $(this).attr("href", "login.html")
            } else {
                $(this).attr("href", "javascript:;")
            }
        }
    })

}

// 动态渲染数据 + 轮播效果和幻灯片效果
function indexRender() {
    $.ajax({
        url: "http://10.31.155.75/mogujie/php/indexData.php",
        dataType: "json"
    }).done(function(res) {
        console.log(res)
        let wriper = res.wriper // 获取今日抢购区域幻灯片效果的数据
        let lovedata = res.lovedata // 获取猜你喜欢模块的数据
        let womenwear = res.womenwear // 获取女鞋&包包模块的数据
        console.log(womenwear)

        // 渲染今日必抢模块幻灯片区域数据
        let str = ""
        let clonedata = ""
        for (let i = 0; i < wriper.length; i++) {
            str += `
                    <div class="item_box fl">
                        <div class="good_item">
                            <a href="javascript:;">
                                <img src="${wriper[i].url}" alt="">
                            </a>
                            <a href="javascript:;" class="good_title">${wriper[i].title}</a>
                            <div class="good_price"><em>¥${wriper[i].price}</em></div>
                        </div>
                    </div>
                `
            if (i == 3) {
                clonedata = str
            }
        }
        $(".oslide_banner").html(str + clonedata)

        // 渲染猜你喜欢模块数据
        let newstr = ""
        $.each(lovedata, function(index, value) {
            newstr += `
                <li class="love_good">
                    <a href="" class="render_data">
                        <img src="${value.url}" alt="" class="render_img">
                        <p>${value.title}</p>
                        <span class="render_price">￥${value.price}</span>
                        <span class="render_salenum">
                            <img src="https://s18.mogucdn.com/p2/160908/upload_27g4f1ch6akie83hacb676j622b9l_32x30.png"
                            alt="">
                            <strong>${value.salenum}</strong>
                        </span>
                    </a>
                </li>
            `
        })
        $(".love_data").html(newstr)

        // 渲染女鞋&包包模块数据
        let wearstr = ""
        let wearcount = 0
        for (let i = 0; i < womenwear.length; i++) {
            wearstr += `
                <div class="mid_banner mid_banner${wearcount}">
            `
            for (let j = 0; j < 6; j++) {
                wearstr += `
                    <div class="swiper_img fl">
                        <a href="javascript:;">
                            <div class="swiper_pic">
                                <img src="${womenwear[i].url}" alt="">
                            </div>
                            <p class="swiper_img_title">${womenwear[i].title}</p>
                            <p class="swiper_img_price">
                                <em>¥</em>
                                <span>${womenwear[i].price}</span>
                            </p>
                        </a>
                    </div>
                `
                i++
            }
            i--
            wearcount++
            wearstr += "</div>"
        }
        $('.womenbags .mid_content').html(wearstr)

        // 女鞋&包包区域轮播效果
        let timed = null
        const dots = $(".womenbags .swiper_dot a")
        const wriperwidth = $(".womenbags .mid_content").innerWidth()
        const midBanners = $(".womenbags .mid_banner")
        const midWriper = $(".womenbags .mid_wriper") // 包裹轮播区域的盒子 
        let number = 0 // 定义轮播盒子所在大盒子中的索引号

        // 女装&包包轮播移动动画效果
        function wearmove() {
            if (number == 4) {
                midBanners.eq(number).animate({
                    left: -wriperwidth
                })
                number = -1
                midBanners.eq(number + 1).css({
                    left: wriperwidth
                })
                midBanners.eq(number + 1).animate({
                    left: 0
                })
            } else {
                midBanners.eq(number).animate({
                    left: -wriperwidth
                })
                midBanners.eq(number + 1).css({
                    left: wriperwidth
                })
                midBanners.eq(number + 1).animate({
                    left: 0
                })
            }
            number++
            dots.eq(number).addClass("active_color").siblings("a").removeClass("active_color")
        }
        timed = setInterval(function() {
            wearmove()
        }, 4000)
        midWriper.hover(function() {
            clearInterval(timed)
        }, function() {
            timed = setInterval(function() {
                wearmove(number)
            }, 4000)
        })

        function throttle(fn, waittime) { // 节流函数
            let lasttime = 0
            return function(ev) {
                let nowtime = Date.now()
                if (nowtime - lasttime >= waittime) {
                    fn.apply(this, arguments)
                    lasttime = nowtime
                }
            }
        }

        function fn() { // 小圆点鼠标移入事件处理函数
            clearInterval(timed)
            let dotnum = $(this).index()
            if (dotnum !== number) {
                if (dotnum < number) {
                    midBanners.eq(number).animate({
                        left: wriperwidth
                    })
                    midBanners.eq(dotnum).css("left", -wriperwidth)
                    midBanners.eq(dotnum).animate({
                        left: 0
                    })

                } else if (dotnum > number) {
                    midBanners.eq(number).animate({
                        left: -wriperwidth
                    })
                    midBanners.eq(dotnum).css({
                        left: wriperwidth
                    })
                    midBanners.eq(dotnum).animate({
                        left: 0
                    })
                }
                number = dotnum
                console.log(number)
                dots.eq(number).addClass("active_color").siblings("a").removeClass("active_color")
            }
        }
        dots.on("mouseover", throttle(fn, 600)) // 轮播下面的小圆点鼠标移入事件

        // 今日抢购区域幻灯片效果
        const prev_btn = $(".prev_btn") // 左边点击按钮
        const next_btn = $(".next_btn") // 右侧点击按钮
        const swiperbox = $(".slide") // 展示轮播的大盒子
        const movebox = $(".oslide_banner") // 点击按钮移动的盒子
        const itemlist = $(".item_box") // 幻灯片商品项
        let num = 0 //存储索引
        const movenum = 4 // 一次移动的图片长度
        let timer = null

        swiperbox.hover(function() {
            prev_btn.show()
            next_btn.show()
            clearInterval(timer)
        }, function() {
            prev_btn.hide()
            next_btn.hide()
            timer = setInterval(function() {
                next_btn.click()
            }, 4000)
        })

        timer = setInterval(function() {
            next_btn.click()
        }, 4000)

        console.log(movebox)
        let moveWidth = movebox.width()

        console.log(moveWidth)

        next_btn.on("click", function() {
            num += 1
            move()
        })

        prev_btn.on("click", function() {
            num -= 1
            move()
        })

        // 1.改变布局 - 无缝运动都要改变布局。
        // 计算ul列表的宽度
        movebox.css({
            width: $(".item_box").length / movenum * moveWidth
        })

        //封装图片运动的过程
        function move() {
            // 最后一张图
            let lastitem = Math.ceil(itemlist.length / movenum) - 1 //减1的原因是由于索引从0开始

            //判断如果是最后一张，改变picul位置。
            if (num > lastitem) { //当前的索引>5,先重置picul的位置，然后位置改变
                movebox.css('left', 0)
                num = 1
            }
            if (num < 0) {
                movebox.css('left', -moveWidth * lastitem)
                num = lastitem - 1 // 要减去克隆那块
            }
            movebox.stop(true).animate({ //stop:保证运动完成
                left: -num * moveWidth
            }, 300)
        }
    })
}

// 倒计时效果
function countDown(time) { // time: 抢购时间
    const hour = $(".time_hour")
    const minute = $(".time_minute")
    const second = $(".time_second")
    let date = new Date(time)
    let nowDate = new Date()
    let t = date - nowDate
    let h = Math.floor(t / 1000 / 60 / 60)
    h = h < 10 ? "0" + h : h
    let m = Math.floor(t / 1000 / 60 % 60)
    m = m < 10 ? "0" + m : m
    let s = Math.floor(t / 1000 % 60)
    s = s < 10 ? "0" + s : s
    hour.html(h)
    minute.html(m)
    second.html(s)
}

// 楼梯效果和返回顶部效果
function stairEffect() {
    const backtop = $(".nav_backtop a")
    backtop.on("click", function(ev) {
        toPosition(0, 1000)
        ev.stopPropagation()
        return false
    })

    const nav_love = $(".nav_love a")
    nav_love.on("click", function(ev) {
        let h = $(".lovely").offset().top - 200
        toPosition(h, 1000)
        ev.stopPropagation()
        return false
    })

    const nav_babywear = $(".nav_babywear a")
    nav_babywear.on("click", function(ev) {
        let h = $(".bobywear").offset().top - 200
        toPosition(h, 1000)
        ev.stopPropagation()
        return false
    })

    const nav_furnishings = $(".nav_furnishings a")
    nav_furnishings.on("click", function(ev) {
        let h = $(".furnishings").offset().top - 200
        toPosition(h, 1000)
        ev.stopPropagation()
        return false
    })

    const nav_underwear = $(".nav_underwear a")
    nav_underwear.on("click", function(ev) {
        let h = $(".underwears").offset().top - 200
        toPosition(h, 1000)
        ev.stopPropagation()
        return false
    })

    const nav_menwear = $(".nav_menwear a")
    nav_menwear.on("click", function(ev) {
        let h = $(".menshoes").offset().top - 200
        toPosition(h, 800)
        ev.stopPropagation()
        return false
    })

    const nav_womenshoes = $(".nav_womenshoes a")
    nav_womenshoes.on("click", function(ev) {
        let h = $(".womenbags").offset().top - 150
        toPosition(h, 800)
        ev.stopPropagation()
        return false
    })

    const nav_womenwear = $(".nav_womenwear a")
    nav_womenwear.on("click", function(ev) {
        let h = $(".womenwear").offset().top - 200
        toPosition(h, 800)
        ev.stopPropagation()
        return false
    })

    const nav_daybuy = $(".nav_daybuy a")
    nav_daybuy.on("click", function(ev) {
        let h = $(".daybuy").offset().top - 100
        toPosition(h, 800)
        ev.stopPropagation()
        return false
    })

    function toPosition(h, movetime) {
        $("html").animate({ scrollTop: h }, movetime)
    }
}


export {
    loginState,
    twoMenu,
    fixedHead,
    carbuy,
    indexRender,
    countDown,
    stairEffect
}